/**
 * Created by Administrator on 2016/12/17.
 */
/**
 * Created by Administrator on 2016/12/17.
 */
/**
 * Created by Administrator on 2016/12/16.
 */
$(function () {
    init();
    uploadImg();
    $('.addWorkers,.dealAll').addClass("disabled");

}),
    $(".form-date").datetimepicker(
        {
            language: "zh-CN",
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0,
            format: "yyyy-mm-dd"
        });
/***弹出工地数据管理页面***/
$('.tab2Content2').click(function () {
    layer.open({
        title: '工地数据管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../../../siteData/siteDate.html'
    })
});
/*********弹出班组资金管理页面************/
$('.tab2Content3').click(function () {
    layer.open({
        title: '班组资金管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../edit/projectDetailsEdit/projectEdit.html'
    })
});
/*************弹出项目资金管理页面**************/
$('.tab2Content4').click(function () {
    layer.open({
        title: '项目资金管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../edit/projectDetailsEdit/projectEdit.html'
    })
});
/*********加载分包班组信息表***********/

function init() {
    $("#teamTable").bootstrapTable({
        method: 'post',
        url: '../projectDetailsView/projectView.json',
        onLoadSuccess: function (data) {
            //console.log(data);
        },
        onClickCell: function (field, value, row, $element) {
            //console.log(value);
            console.log(field);
            if (field == "projectCourse") {
                layer.open({
                    title: '查看项目详情',
                    shadeClose: true,
                    shade: 0.8,
                    type: 2,
                    fix: false,
                    maxmin: true,
                    area: ['100%', '100%'],
                    content: '../projectBasicData/basicDetails/view/projectDetailsView/projectView.html'
                })
            }
        }
    });
}
function responseHandler(res) {
    var needData = {
        rows: res.data.list,
        total: res.data.total
    }
    return needData;
}
function teamTableQuery(params) {
    params['pageNum'] = (params.offset / params.limit) + 1;
    params.pageSize = params.limit;
    return params;
}
function addRemoveFmt(index, row, val) {
    return "<button class='btn btn-default'>查看/编辑</button>"
}

///////////////封装ajax //////////////////////////
function sendDigital(type, url, data) {

}
/*********点击确定按钮，将信息保存到后台****************/
var obj1 = location.search;
obj = obj1.slice(1).split("&");
console.log(obj1);
var arg = {};
for (var i = 0; i < obj.length; i++) {
    var result = "";
    result = obj[i].split("=")
    arg[result[0]] = result[1];

}
console.log(arg);
// $('input[type="text"]');
/****点击分包班组承包人input框，弹出分包班组承包人列表页面*****/
$('input[data-name="userName"]').focus(function () {

    $.ajax({
        type: 'post',
        url: `http://192.168.59.3:8082/console/projectInfo/findUserListByRole`,
        data: JSON.stringify({"pageNum": 1, "pageSize": 10, "roleId": 2}),
        contentType: 'application/json',
        success: function (data) {
            console.log(data);
            localStorage.contractor = data;
        },
        error: function (err) {
            console.log(err);
        }
    });

    //console.log(data);
    layer.open({
        title: "分包班组承包人列表",
        type: 2,
        area: ['50%', '50%'],
        maxmin: true,
        fix: false,
        shadeClose: true,
        content: `userName/userName.html`
    })
});
$('input[data-name="userName"]').blur(function () {
    var moved = 0;
    var teamInfo = JSON.parse(sessionStorage.getItem("teamInfo"));
    var timer = setInterval(function () {
        moved++;
        teamInfo = JSON.parse(sessionStorage.getItem("teamInfo"));
        console.log(teamInfo);
        if (teamInfo.realName || teamInfo.realName != this.value) {
            this.value = teamInfo.realName;
            clearInterval(timer);
            timer = null;
            // sessionStorage.clear("teamInfo");
        }
        if (moved >= 3) {
            clearInterval(timer);
            timer = null;
        }
    }.bind(this), 90);
    /*****************点击确定保存页面信息**************************/
    $('.resure').click(function () {
        var oIpt = $('[data-name]');
        //console.log(oIpt);
        var str = {};
        for (var i = 0; i < oIpt.length; i++) {
            if (oIpt[i].nodeName == "INPUT") {
                str[$(oIpt[i]).attr('data-name')] = $(oIpt[i]).val();
                if ($(oIpt[i]).attr('data-name') == "totalPrice") {
                    str["totalPrice"] = parseInt($(oIpt[i]).val());
                }
            }
            ;
            if ($(oIpt[i]).attr("data-name") == "teamAuthorization") {
                var oA = "";
                var a1 = $(oIpt[i]).find("input[type='file']");
                a1.each(function (i, e) {
                    if (e.files[0]) {
                        oA += "imgs/" + e.files[0].name + ",";
                    }
                });
                oA = oA.slice(0, oA.length - 1);
                str["teamAuthorization"] = oA;
                console.log(oA)
            }
            ;
        }

        str["isValid"] = 0;
        str["projectCode"] = arg.projectCode;
        str["userCode"] = teamInfo.userCode;
        str["userName"] = teamInfo.realName;
        console.log(str);
        /* oIpt.each(function(i,c){
         var key=$(c).attr('data-name');
         var value=$(c).val();
         if(key=="projectTypeId"){
         str[key]=parseInt(value);
         }else if(key=="id"){
         str[key]=parseInt(value);
         }else if(key=="totalPrice"){
         str[key]=parseInt(value);
         }else{
         str[key]=value;
         }
         });*/
        $.ajax({
            type: "post",
            url: `http://192.168.59.3:8082/console/projectInfo/saveTeam`,
            contentType: "application/json",
            dataType: 'json',
            data: JSON.stringify(str),
            success: function (data) {
                console.log(data);
                var oD = data;
                $('.addWorkers,.dealAll').removeClass("btn-default");
                $('.addWorkers').addClass("btn-warning");
                $('.dealAll').addClass("btn-info");
                $('.addWorkers,.dealAll').removeClass("disabled");

                // parent.layer.closeAll();
                //var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                //parent.layer.close(index);
                /**********点击新增工人弹出 新的页面*************/

                $('.addWorkers').click(function () {
                    //console.log(111);
                    $.ajax({
                        type: "post",
                        url: `http://192.168.59.3:8082/console/projectInfo/findUserListByRole`,
                        data: '{"pageNum":1,"pageSize":10,"roleId":1}',
                        contentType: 'application/json',
                        success: function (data) {
                            console.log(data);
                            // localStorage.contractor=data
                            layer.open({
                                title: '选择建筑工人',
                                shadeClose: true,
                                shade: 0.8,
                                type: 2,
                                fix: false,
                                maxmin: true,
                                area: ['50%', '50%'],
                                content: `../addWorkers/addWorkers.html${obj1}&teamId=${oD.data}`,
                                end: function (d) {
                                    console.log(d);
                                    $("#teamDetailTable").bootstrapTable({
                                        method: 'get',
                                        url: `http://192.168.59.3:8082/console/projectInfo/findWorkerByTeam/${oD.data}`,
                                        onLoadSuccess: function (data) {
                                            // console.log(data);
                                            $('.bs-checkbox').hide();
                                        }
                                    });
                                }

                            })
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    });

                });
            },
            error: function (err) {
                console.log(err);
                layer.open({
                    title: "提示",
                    type: 1,
                    area: ['20%', '20%'],
                    maxmin: true,
                    fix: false,
                    shadeClose: true,
                    content: `<h4 style="text-align: center;">请填写完整信息！</h4>`
                });
            }
        });

    });
});
/****点击班组类别input框，弹出班组类别页面*****/

$('input[data-name="teamTypeName"]').focus(function () {
    $.ajax({
        type: 'get',
        url: `http://192.168.59.3:8082/console/teamTypeInfo/getTeamTypeInfoList?pageNum=1&pageSize=10`,
        // data:JSON.stringify({"pageNum":1,"pageSize":10,}),
        contentType: 'application/json',
        success: function (data) {
            console.log(JSON.parse(data).data);
            // localStorage.contractor=data;
            var teamTypeInfo = JSON.parse(sessionStorage.getItem("teamTypeInfo"));
            console.log(teamTypeInfo);

            var arr = JSON.parse(data).data;
            var str = "";
            for (var i = 0; i < arr.length; i++) {
                for (var key in arr[i]) {
                    str += "&" + key + "=" + arr[i][key]
                }
            }
            console.log(str);
            layer.open({
                title: "分包班组承包人列表",
                type: 2,
                area: ['50%', '50%'],
                maxmin: true,
                fix: false,
                shadeClose: true,
                content: `teamType/teamType.html?${str.slice(1)}`
            })
        },
        error: function (err) {
            console.log(err);
        }
    });
});
$('input[data-name="teamTypeName"]').blur(function () {
    var moved = 0;
    var teamTypeInfo = "";
    console.log(teamTypeInfo);
    var timer = setInterval(function () {
        moved++;
        teamTypeInfo = JSON.parse(sessionStorage.getItem("teamTypeInfo"));
        if (teamTypeInfo.teamTypeName || teamTypeInfo.teamTypeName != this.value) {
            this.value = teamTypeInfo.teamTypeName;
            clearInterval(timer);
            timer = null;
            //sessionStorage.clear("teamTypeInfo");
        }
        if (moved >= 3) {
            clearInterval(timer);
            timer = null;
        }
    }.bind(this), 100)

})


/////////////////////////////////////////
/************************/


////*********上传图片************///
function uploadImg() {
    var host = "http://192.168.59.2:7090/image";
    var firstName = "http://choosefine-uat.oss-cn-hangzhou.aliyuncs.com/";

    if ($('[data-pic]')) {
        $('[data-pic]')

            .html(`
            <img src="#">
            <form action=${host} method="post" enctype="multipart/form-data" target="hide_frame" style="display: none;">
              <input name="name">
              <input type="file" name="file"/>
            <form>
          `)
            .find('[type="file"]').on('change',
            function () {
                var lastName = "console/user/" + (new Date()).getTime() + '-' + this.files[0].name;
                $(this).prev().val(lastName);
                $(this).parent().submit();
                console.log(firstName + lastName);
                setTimeout(function () {
                    $(this).parent().prev().attr('src', firstName + lastName);
                }.bind(this), 12000)
            });
        $('[data-pic]')
            .each(function (i, div) {
                var dataName = $(div).attr('data-pic');

                $(div).find('img').attr('data-name', dataName)
            });

        $('[data-pic]').find('img')

            .on('click', function () {
                $(this).parent().find('[type="file"]').click();
            })

        $(document.body).append(`
            <iframe name="hide_frame" style="display: none">
          `)
    }

    if ($("[data-purl]")) {
        var images = $("[data-purl]").find('img');
        var purl = "";

        images.each(function (i, img) {
            purl = $(img).parent().attr('data-purl');
            $(img).attr('src', purl);
        })
    }
}




